//
//  CacheData.swift
//  puretennis
//
//  Created by Derek Zheng on 1/20/15.
//  Copyright (c) 2015 IYE Technologies. All rights reserved.
//

import Foundation
import CoreData

class CacheData: NSManagedObject{
    @NSManaged var key: String
    @NSManaged var type: String
    @NSManaged var value: AnyObject
    
    
    class func saveOrUpdate(key: String, value: AnyObject){
        
        let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        
        if let moc = appDelegate.managedObjectContext {
            
            if let cacheData: AnyObject = self.queryCacheData(key){
                
                cacheData.setValue(value, forKey: "value")
                
            }else{
                
                let entity = NSEntityDescription.entityForName("CacheData", inManagedObjectContext: moc)
                let newItem = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: moc)
                
                newItem.setValue(key, forKey: "key")
                newItem.setValue(_stdlib_getTypeName(value), forKey: "type")
                newItem.setValue(value, forKey: "value")
            }
            
            var error: NSError?
            
            if !moc.save(&error) {
                Utils.debug("Could not save \(error), \(error?.userInfo)")
            }
        }
    }
    

    class func queryCacheData(key: String) -> NSManagedObject?{
        let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        if let moc = appDelegate.managedObjectContext {
            var request = NSFetchRequest(entityName: "CacheData")
            request.predicate = NSPredicate(format: "(key = %@)", key)
            var results: [NSManagedObject] = moc.executeFetchRequest(request, error: nil) as [NSManagedObject]
            if(results.count == 0){
                return nil
            }
            return (results[0] as NSManagedObject)
        }
        return nil
    }
    
    class func query(key: String) -> AnyObject?{
        return self.queryCacheData(key)?.valueForKey("value")
    }
    
    class func remove(key: String){
        let obj = queryCacheData(key)
        if(obj != nil){
            let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
            if let moc = appDelegate.managedObjectContext {
                moc.deleteObject(obj!)
                moc.save(nil)
            }
        }
    }
}
